<template>
  <div class="app-container">
    <!-- 搜索条件 -->
    <el-form :model="queryParams" ref="queryForm"  label-width="68px">
      <el-row>
        <el-col :span="4" v-if="queryParams.deptId !== 0">
          <el-form-item label="上级部门" prop="deptId">
            <treeselect
              v-model="queryParams.deptId"
              :options="deptOptions"
              :normalizer="normalizer"
              placeholder="选择上级部门"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 顶部按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
    </el-row>

    <!-- 数据列表 -->
    <el-table v-loading="loading" :data="dataList">
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column
        label="假期开始时间"
        align="center"
        prop="holidayStart"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="假期结束时间"
        align="center"
        prop="holidayEnd"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="假期部门"
        align="center"
        prop="deptId"
        :show-overflow-tooltip="true"
        :formatter="deptFormatter"
      ></el-table-column>
      <el-table-column label="是否月假" align="center" >
                <template slot-scope="scope">
                    <el-switch
                        v-model="scope.row.isHoliday"
                        active-value="1"
                        inactive-value="0"
                        @change="handleStatusChange(scope.row)"
                    />
                </template>
            </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="修改时间"
        align="center"
        prop="modifyTime"
        width="160"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.modifyTime) }}</span>
        </template>
      </el-table-column>-->

      <!-- 表格操作列 -->
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            circle
            type="success"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          />
          <el-button
            size="mini"
            circle
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增 OR 修改对话框 -->
    <el-dialog :title="title" v-if="open" :visible.sync="open" width="35%">
      <el-form ref="form" :model="form" label-width="120px" :rules="rules">
        <el-row>
          <el-col :span="13">
            <el-form-item label="假期开始时间" prop="holidayStart">
              <el-date-picker
                v-model="form.holidayStart"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="13">
            <el-form-item label="假期结束时间" prop="holidayEnd">
              <el-date-picker
                v-model="form.holidayEnd"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptionsEnd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="13" v-if="form.deptId !== 0">
            <el-form-item label="上级部门" prop="deptId">
              <treeselect
                v-model="form.deptId"
                :options="deptOptions"
                :normalizer="normalizer"
                placeholder="选择上级部门"
              />
            </el-form-item>
          </el-col>
          <el-col :span="13">
                    <el-form-item label="是否月假" prop="isHoliday">
                        <el-switch
                            v-model="form.isHoliday"
                            active-value="1"
                            inactive-value="0"
                        />
                    </el-form-item>
                </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  findPageList,
  addHoliday,
  deleteHoliday,
  findHolidayById,
  updateHoliday
} from "@/api/attendance/holiday";
import { listDept, treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "holiday",
  components: { Treeselect },
  data() {
    return {
      pickerOptions: this.handelDate(),
      pickerOptionsEnd: this.handelDateEnd(),
      dialogVisible: true,
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 数据列表
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deptId: [{ required: true, message: "必填", trigger: "blur" }],
        holidayStart: [{ required: true, message: "必填", trigger: "blur" }],
        holidayEnd: [{ required: true, message: "必填", trigger: "blur" }]
      },
      //考勤部门
      deptOptions: undefined,
      deptTableOption: undefined
    };
  },

  created() {
    this.getList();
    this.getTreeselect();
    listDept().then(resp => {
      this.deptTableOption = resp.data;
    });
  },
  methods: {
    deptFormatter(row) {
      return this.getLable(this.deptTableOption, row.deptId, "id", "name");
    },

    /**
     * 根据接收到值显示对应的中文name
     * list：数据源
     * id：传入的值
     * value : list中id对应的key名称
     * lable: list中value对应的key名称
     */
    getLable(list, id, value, lable) {
      if (id != "" && Array.isArray(list) && list.length != 0) {
        return !list.find(item => item[value] == id)
          ? id
          : list.find(item => item[value] == id)[lable];
      } else {
        return id;
      }
    },
    handleStatusChange(row){
            // for(let i = 0; i < row.children.length; i ++) {
            //     row.children[i].isHoliday = row.isHoliday;
            // }
            updateHoliday(row).then(resp => {
              if (resp.code === 200) {
                this.msgSuccess(resp.message);
                this.open = false;
                this.getList();
              } else {
                this.msgError(resp.message);
              }
            });
        },

    getTreeselect() {
      listDept().then(response => {
        this.deptOptions = this.handleTree(response.data, "id");
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      findPageList(this.queryParams).then(response => {
        this.dataList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      console.log(this.queryParams);
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 新增
    handleAdd() {
      this.title = "新增假期";
      this.open = true;
      this.reset();
      // this.getTreeselect();
    },
    // 提交表单重置
    reset() {
      this.form = {
        id: undefined,
        holidayStart: undefined,
        holidayEnd: undefined,
        deptId: undefined,
        isHoliday: undefined
      };
      this.resetForm("form");
    },
    // 修改
    handleUpdate(row) {
      this.title = "修改假期";
      this.open = true;
      this.reset();
      // this.getTreeselect();
      findHolidayById(row.id).then(resp => {
        this.form = resp.data;
        console.log(this.form);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 新增 OR 修改 提交
    submitForm() {
      // console.log(this.form.holidayEnd)
      // console.log(this.form.holidayStart)
      // console.log(new Date(this.form.holidayStart).getTime())
      // console.log(new Date(this.form.holidayEnd).getTime())
      if (
        new Date(this.form.holidayEnd).getTime() -
          new Date(this.form.holidayStart).getTime() <
        0
      ) {
        this.$message({
          type: "error",
          message: "结束时间必须大于等于开始时间"
        });
        return
      }
      this.$refs["form"].validate(valid => {
        if (this.form.id) {
          if (valid) {
            updateHoliday(this.form).then(resp => {
              if (resp.code === 200) {
                this.msgSuccess(resp.message);
                this.open = false;
                this.getList();
              } else {
                this.msgError(resp.message);
              }
            });
          }
        } else {
          if (valid) {
            addHoliday(this.form).then(resp => {
              if (resp.code === 200) {
                this.msgSuccess(resp.message);
                this.open = false;
                this.getList();
              } else {
                this.msgError(resp.message);
              }
            });
          }
        }
      });
    },
    // 删除
    handleDelete(row) {
      deleteHoliday(row.id).then(resp => {
        this.msgSuccess(resp.message);
        this.open = false;
        this.getList();
      });
    },
    handelDate() {
      return {
        // disabledDate : 设置禁用状态，参数为当前日期，要求返回 Boolean
        disabledDate(time) {
          // return time.getTime() > Date.now() // 只能选今天之前的日期
          return time.getTime() < Date.now() - 1000 * 60 * 60 * 24; // 只能选今天之后的日期
        }
      };
    },
    handelDateEnd() {
      return {
        // disabledDate : 设置禁用状态，参数为当前日期，要求返回 Boolean
        disabledDate(time) {
          // return time.getTime() > Date.now() // 只能选今天之前的日期
          return time.getTime() < Date.now() - 1000 * 60 * 60 * 24; // 只能选今天之后的日期
        }
      };
    }
  }
};
</script>

<style>
</style>